<template>
	<div class="class-delay-chart">
		<div ref="chartRef" class="chart-container" style="width:100%;height:100%;">
			<div v-if="loading" class="chart-loading"><el-skeleton :rows="8" animated /></div>
			<div v-else-if="!hasValidData" class="chart-empty"><el-empty description="暂无数据" /></div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
	data: { type: Object, default: null },
	loading: { type: Boolean, default: false }
});

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
let isDestroyed = false;

// 检查是否有有效数据
const hasValidData = computed(() => {
	if (!props.data || typeof props.data !== 'object') return false;
	return Array.isArray(props.data.categories) && props.data.categories.length > 0 && 
		   Array.isArray(props.data.totalCounts) && props.data.totalCounts.length > 0 && 
		   Array.isArray(props.data.delayCounts) && props.data.delayCounts.length > 0 && 
		   Array.isArray(props.data.delayRates) && props.data.delayRates.length > 0;
});

// 初始化图表
const initChart = () => {
	if (isDestroyed || !chartRef.value) return;
	
	try {
		if (chartInstance) {
			chartInstance.dispose();
			chartInstance = null;
		}
		chartInstance = echarts.init(chartRef.value);
	} catch (error) {
		console.error('ClassDelayChart 初始化图表失败:', error);
	}
};

// 渲染图表
const renderChart = () => {
	if (isDestroyed || !chartRef.value || !chartInstance || !hasValidData.value) {
		return;
	}
	
	try {
		const pieData = (props.data.categories || []).map((category: string, index: number) => ({
			name: category,
			value: (props.data.delayCounts || [])[index],
			total: (props.data.totalCounts || [])[index],
			rate: (props.data.delayRates || [])[index]
		}));
		
		const option = {
			title: {
				text: '各分类延期情况',
				left: 'center',
				textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' }
			},
			tooltip: {
				trigger: 'item',
				formatter: (params: any) => {
					const data = params.data;
					return `
						<div style="padding: 8px;">
							<div style="font-weight: bold; margin-bottom: 8px;">${data.name}</div>
							<div style="color: #409eff;">总计划数: ${data.total}</div>
							<div style="color: #f56c6c;">延期数量: ${data.value}</div>
							<div style="color: #e6a23c;">延期率: ${data.rate}%</div>
							<div style="color: #909399;">占比: ${params.percent}%</div>
						</div>
					`;
				}
			},
			legend: {
				type: 'scroll',
				orient: 'horizontal',
				bottom: 10,
				data: props.data.categories || [],
				itemGap: 20,
				textStyle: { fontSize: 12 }
			},
			series: [
				{
					name: '延期分布',
					type: 'pie',
					radius: ['40%', '70%'],
					center: ['50%', '45%'],
					avoidLabelOverlap: false,
					itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
					label: {
						show: true,
						position: 'outside',
						formatter: (params: any) => `${params.name}\n${params.data.value}项\n${params.percent}%`,
						fontSize: 11,
						fontWeight: 'bold'
					},
					emphasis: {
						label: { show: true, fontSize: 14, fontWeight: 'bold' },
						itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' }
					},
					labelLine: { show: true, length: 15, length2: 20, smooth: 0.3 },
					data: pieData,
					animationType: 'scale',
					animationDelay: (idx: number) => Math.random() * 200,
					color: [
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#667eea' }, { offset: 1, color: '#764ba2' } ]),
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#f093fb' }, { offset: 1, color: '#f5576c' } ]),
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#4facfe' }, { offset: 1, color: '#00f2fe' } ]),
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#43e97b' }, { offset: 1, color: '#38f9d7' } ]),
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#fa709a' }, { offset: 1, color: '#fee140' } ]),
						new echarts.graphic.LinearGradient(0, 0, 1, 1, [ { offset: 0, color: '#a8edea' }, { offset: 1, color: '#fed6e3' } ])
					]
				}
			]
		};
		
		chartInstance.setOption(option, true);
		chartInstance.resize();
	} catch (error) {
		console.error('ClassDelayChart 渲染图表失败:', error);
	}
};

// 监听数据变化并渲染图表
watch(() => props.data, () => {
	if (isDestroyed || props.loading || !hasValidData.value) return;
	
	nextTick(() => {
		if (!chartInstance && chartRef.value) {
			initChart();
		}
		renderChart();
	});
}, { deep: true });

// 监听加载状态变化
watch(() => props.loading, (loading) => {
	if (isDestroyed) return;
	
	if (!loading && hasValidData.value) {
		nextTick(() => {
			if (!chartInstance && chartRef.value) {
				initChart();
			}
			renderChart();
		});
	}
});

onMounted(() => {
	nextTick(() => {
		if (chartRef.value && !isDestroyed) {
			initChart();
			
			const handleResize = () => {
				if (chartInstance && !isDestroyed) {
					chartInstance.resize();
				}
			};
			window.addEventListener('resize', handleResize);
			
			if (hasValidData.value && !props.loading) {
				renderChart();
			}
		}
	});
});

onUnmounted(() => {
	isDestroyed = true;
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
});
</script>

<style lang="scss" scoped>
.chart-container { 
	width: 100%; 
	height: 100%; 
	min-height: 344px; 
	position: relative; 
}

.chart-loading, .chart-empty { 
	position: absolute; 
	top: 0; 
	left: 0; 
	right: 0; 
	bottom: 0; 
	background: rgba(255,255,255,0.9); 
	display: flex; 
	align-items: center; 
	justify-content: center; 
	z-index: 10; 
	padding: 20px; 
}

@media (max-width: 768px) { 
	.chart-container { 
		min-height: 300px; 
	} 
}
</style>